package com.tjshop.android.util;

import org.apache.commons.codec.binary.Hex;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 对密码进行加密和验证的类
 */
public class MD5Utils {

	static MessageDigest md = null;

	static {
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException ne) {

		}
	}

	/**
	 * 对一个文件求他的md5值
	 * 
	 * @param f
	 *            要求md5值的文件
	 * @return md5串
	 */
	public static String md5(File f) {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(f);
			// 100KB each time
			byte[] buffer = new byte[102400];
			int length;
			long loopCount = 0;
			while ((length = fis.read(buffer)) != -1) {
				md.update(buffer, 0, length);
				loopCount++;
			}
			return new String(Hex.encodeHex(md.digest()));
		} catch (FileNotFoundException e) {

			return null;
		} catch (IOException e) {

			return null;
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String md5(String string) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(
					string.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}
		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();

	}

	/*
	 * test function long begin =System.currentTimeMillis();
	 * System.out.println(md5(new File("G:/BT/PremierePro_6_LS7.7z"))); long end
	 * =System.currentTimeMillis();
	 * System.out.println("time:"+((end-begin)/1000)+"s");
	 * System.out.println(md5("hello world"));
	 */
}
